package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Host {
    private String hostName;
    private String appBase;
    private Map<String, Context> contextMap = new HashMap<>();

    public Host(String hostName, String appBase) {
        this.hostName = hostName;
        this.appBase = appBase;
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private Context buildContext(String path) { // demo1
        Context context = new Context();
        SAXReader saxReader = new SAXReader();

        try {
            // 1. 加载web.xml
            File file = new File(appBase + "/" + path + "/WEB-INF/web.xml");
            Document document = saxReader.read(file);
            Element rootElement = document.getRootElement();

            // 2. 读取标签<servlet> </servlet>
            List<Element> selectNodes = rootElement.elements("servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.element("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.element("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 3. 根据servlet-name的值找到url-pattern
                List<Element> mappings = rootElement.elements("servlet-mapping");
                for (Element mapping : mappings) {
                    if (servletName.equals(mapping.element("servlet-name").getText())) {
                        // /lagou
                        String urlPattern = mapping.element("url-pattern").getStringValue();
                        // 4. 实例化LagouServlet并设置到容器
                        context.getWrapperMap().put(urlPattern, new Wrapper(appBase, path, servletClass));
                        continue;
                    }
                }
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return context;

    }


    public void init() {
        // 1. 读取app下的文件夹，也就是webapps目录
        File baseDir = new File(appBase);
        if (baseDir.isDirectory()) {
            for (File file : baseDir.listFiles()) {
                if (file.isFile()) {
                    continue;
                }
                // 2. 文件名作为Context的key （demo1）
                String contextName = file.getName();
                // 读取WEB-INF下的web.xml并加载Context
                Context context = buildContext(contextName);

                contextMap.put(contextName, context);
            }
        }
    }

    public HttpServlet getServlet(String url) {
        String[] split = url.split("/");
        // demo1
        Context context = contextMap.get(split[1]);
        if (context == null) {
            return null;
        }

        return context.getServlet(url.replace("/" + split[1], ""));
    }
}
